from django.shortcuts import render, HttpResponse

from utils.tencent.sms import send_single_sms
import random, time
from django.conf import settings
from django import forms
from app01 import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import logging
from django_redis import get_redis_connection

logger = logging.getLogger('log')


def get_code(request):
    """
    发送短信
    登录请求连接 /send/sms?tpl=login
    注册请求连接 /send/sms?tpl=register
    :param request:
    :return:
    """

    code = random.randrange(1000, 9999)
    timeout = 10

    tpl = settings.TEMPLATE_SMS.get(request.POST.get("tpl"))
    number = request.POST.get("pNum")

    result = send_single_sms(number, [code, timeout], tpl)
    logger.info(f"phone number: {number}, code: {code}, result: {result}")
    conn = get_redis_connection("default")  # 默认default
    conn.set(number, code, ex=timeout*60)

    if result['result'] == 0:
        return HttpResponse(True)
    else:
        return HttpResponse(False)


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    pwd = forms.CharField(label="密码", widget=forms.PasswordInput())
    confirm_pwd = forms.CharField(label="确认密码", widget=forms.PasswordInput())
    code = forms.CharField(label="验证码", widget=forms.TextInput())

    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'pwd', 'confirm_pwd', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for _, field in self.fields.items():
            field.widget.attrs['class'] = "form-control"
            field.widget.attrs['placeholder'] = f"请输入{field.label}"


def register(request):
    form = RegisterModelForm()
    return render(request, "app01/register.html", {"form": form})

